package com.fm.jbsql.sql;

import com.fm.jbsql.util.CmdOpt;
import com.fm.jbsql.util.JbsqlException;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: syaroshenko
 * Date: Jul 13, 2006
 * Time: 11:36:27 AM
 * Class to compile SQL-objects and visualize results customized for Sybase jConnect
 */

/**
 * Class to compile SQL-objects and visualize results.
 */
public final class SQLScriptCompilerJConnect extends SQLScriptCompiler {
    private static final Logger logger = Logger.getLogger("com.fm.jbsql.sql.SQLScriptCompilerJConnect");
	
    
    protected void execSQL(final Connection con, DbDriver drv, final String query, final CmdOpt cmdopt) throws SQLException,JbsqlException {
        Statement stmt = null;
        boolean results = false;
        int rowsAffected=0;
        
        try {
            stmt = con.createStatement();
            stmt.setEscapeProcessing(false);
            results=stmt.execute(query);
            drv.checkForWarning(stmt);
        } catch (SQLException ex) {
            if ( drv.checkForWarning(ex) ) {
               	if ( stmt != null ) stmt.cancel();
                throw ex;
            }
        }
        
		do {
			try {
				if(results) {
					ResultSet rs = stmt.getResultSet();
					DbDriver.displayResultSet(rs, cmdopt);
					rs.close();
					rs=null;
				} else {
					rowsAffected = stmt.getUpdateCount();
				}
			} catch (SQLException ex) {
				if ( drv.checkForWarning(ex) ) throw ex;
			}
			results = stmt.getMoreResults();
		} while (results || rowsAffected != -1);
        
    }
}

